<template>
	<view v-if="!loading">
		<view class="goods-detail-container">
			<view class="goods-detail-header" :class="state.scrollStatus ? 'goods-detail-header-bg' : ''"
				:style="{ paddingTop: menuButtonTop + 'px' }">
				<view class="goods-detail-warp">
					<view class="detail-header-back" @click="goBack">
						<u-icon class="detail-header-back-icon"
							:class="state.scrollStatus ? 'detail-header-back-bg' : ''" :size="32"
							:name="state.isCanBack ? 'arrow-left' : 'home'"></u-icon>
					</view>
					<view class="detail-header-content" :style="{ display: state.scrollStatus ? '' : 'none' }">
						<view class="detail-header-content-nav">
							<view class="tab-item" v-for="(item, index) in tabList" :key="index"
								:class="index == state.tabActive ? 'tab-item-active' : ''"
								@click="onCurrentPage(item, index)">
								{{ item.name }}
							</view>
						</view>
					</view>
					<view class="detail-header-right">
						<!-- #ifndef MP -->
						<!-- <u-icon
							class="detail-header-right-icon"
							:class="state.scrollStatus ? 'detail-header-back-bg' : ''"
							:size="32"
							name="zhuanfa"
							@click="state.shareState = true"
						></u-icon> -->
						<u-icon style="margin-left: 20rpx" class="detail-header-right-icon"
							:class="state.scrollStatus ? 'detail-header-back-bg' : ''" :size="32" name="more-dot-fill"
							@click="state.moreState = true"></u-icon>
						<!-- #endif -->
					</view>
				</view>
			</view>
		</view>
		<view>
			<view id="scroll-pic">
				<view>
					<u-swiper height="820" indicator-pos="bottomRight" mode="number"
						:list="state.goodsSpu.spuUrls"></u-swiper>
				</view>
				<view class="goods-title-container">
					<view class="goods-price-warp">
						<view class="goods-price">
							<text class="text-price">{{ state.goodsSpu?.salesPrice }}</text>
						</view>
						<view class="goods-sales"> 已售 {{ state.goodsSpu.salesVolume }} </view>
					</view>
					<view class="coupon-warp" v-if="state.couponList && state.couponList.length > 0">
						<view style="display: flex; align-items: center">
							<view v-for="(item, index) in state.couponList" :key="index">
								<view v-if="index <= 2" class="coupons_css">{{ item.couponName }}
									<view class="leftdot"></view>
									<view class="rightdot"></view>
								</view>
							</view>
						</view>
						<view style="display: flex; justify-content: flex-end">
							<u-button type="error" size="mini" shape="circle" @click="showCoupon">领券</u-button>
						</view>
					</view>
					<view class="goods-title-warp">
						<view class="goods-title">{{ state.goodsSpu.name }}</view>
						<view class="sub-title" v-if="state.goodsSpu.subTitle">{{ state.goodsSpu.subTitle }}</view>
					</view>
					<view class="goods-cell-warp">
						<u-cell-group :border="false">
							<u-cell-item :center="true" :title-style="cellTtitleStyle" hover-class="none"
								:title="state.selectArr ? state.selectArr : '选择规格'" @click="openSkuPopup(1)">
								<template v-slot:icon> <text style="color: #909399; font-size: 24rpx">选择</text>
								</template>
							</u-cell-item>
						</u-cell-group>
					</view>
				</view>
			</view>
			<!-- 用户评价 -->
			<view class="comment-container" id="scroll-comment">
				<view class="comment-warp">
					<view style="padding: 20rpx">
						<u-section color="#2979ff" title="评价" sub-title="查看更多"
							@click="toAppraise(state.goodsSpu.id)"></u-section>
					</view>
					<view class="comment-content" v-for="(item, index) in state.goodsAppraiseList" :key="index">
						<view class="comment-content-title">
							<u-avatar size="mini" :src="item.avatarUrl"></u-avatar>
							<view class="right">
								<view>{{ item.nickName }}</view>
								<view class="create-time"> {{ item.createTime }} </view>
							</view>
						</view>
						<view class="comment-content-goods">
							<u-rate :count="5" :disabled="true" v-model="item.goodsScore"></u-rate>
						</view>
						<view class="content"> {{ item.content }}</view>
						<view class="content-images" v-if="item.picUrls">
							<view class="image-item" v-for="(pic, picIndex) in item.picUrls" :key="picIndex">
								<u-image :border-radius="8" width="100%" height="100%" :src="pic"></u-image>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 商品介绍 -->
			<view class="parse-container" id="scroll-description">
				<view class="parse-warp">
					<view class="u-padding-20">
						<u-section color="#2979ff" title="商品详情" :right="false"></u-section>
					</view>
					<view class="content">
						<u-parse :html="state.goodsSpu.description" @ready="readyHandel"></u-parse>
					</view>
				</view>
			</view>
			<!-- 猜你喜欢 -->
			<view class="like-container" id="scroll-like">
				<u-section color="#2979ff" title="猜你喜欢" :right="false"></u-section>
			</view>
			<waterfall-goods></waterfall-goods>
			<u-gap height="200"></u-gap>
			<view class="navigation">
				<view class="left">
					<view class="item" @click="toHome">
						<u-icon name="home" :size="40"></u-icon>
						<view class="text u-line-1">首页</view>
					</view>
					<view class="item">
						<u-icon name="server-fill" :size="40"></u-icon>
						<view class="text u-line-1">客服</view>
					</view>
					<view class="item car" @click="toCart">
						<u-badge class="car-num" :count="useUserStore().shoppingCartCount" type="error"
							:offset="[-5, -9]"></u-badge>
						<u-icon name="shopping-cart" :size="40"></u-icon>
						<view class="text u-line-1">购物车</view>
					</view>
				</view>
				<view class="right">
					<view class="cart btn u-line-1" @click="openSkuPopup(2)">加入购物车</view>
					<view class="buy btn u-line-1" @click="openSkuPopup(3)">立即购买</view>
				</view>
			</view>
		</view>
	</view>

	<vk-data-goods-sku-popup ref="skuPopup" v-model="skuKey" border-radius="20" :localdata="state.goodsSpu"
		skuArrName="goodsSkuSpecsValues" skuListName="goodsSkus" specListName="goodsSpuSpecs" :mode="skuMode"
		@open="onOpenSkuPopup" @close="onCloseSkuPopup" @add-cart="addCart" @buy-now="buyNow"></vk-data-goods-sku-popup>
	<!-- 领券弹窗 -->
	<u-popup v-model="state.couponState" mode="bottom" :safe-area-inset-bottom="true" :border-radius="20"
		:closeable="true">
		<view class="content u-padding-18">
			<scroll-view scroll-y="true" style="height: 40%">
				<view>
					<coupon-info :list="state.couponList" @handleSuccess="queryCoupon"></coupon-info>
				</view>
			</scroll-view>
		</view>
	</u-popup>
	<!-- 分享弹窗 -->
	<u-popup v-model="state.shareState" :height="200" mode="bottom">
		<!-- 分享按钮 -->
		<!-- #ifdef MP-WEIXIN -->
		<button @tap="goodsShare" open-type="share">
			<u-icon name="weixin-fill" color="rgb(83,194,64)"></u-icon>
		</button>
		<!-- #endif -->
	</u-popup>
	<!-- 更多弹窗 -->
	<u-popup v-model="state.moreState" :height="200" mode="bottom" safe-area-inset-bottom :border-radius="15" closeable>
		<view class="more-popup-container">
			<view class="more-popup-item" @click="toHome">
				<u-icon name="home" color="#2979ff" :size="40"></u-icon>
				<view class="text u-line-1">返回首页</view>
			</view>
			<view class="more-popup-item" @click="handleCollect">
				<u-icon :name="state.goodsSpu.collectId ? 'star-fill' : 'star'" color="#2979ff" :size="40"></u-icon>
				<view class="text u-line-1">{{ state.goodsSpu.collectId ? '取消收藏' : '收藏' }}</view>
			</view>
		</view>
	</u-popup>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, getCurrentInstance, nextTick } from 'vue';
import { onLoad, onPageScroll } from '@dcloudio/uni-app';
import { getById as getSpuById } from '@/api/product/spu';
import { getPage as getAppraisePage } from '@/api/product/appraise';
import { addShoppingCart } from '@/api/order/shoppingCart';
import { addObj as addCollect, deleteObj as deleteCollect } from '@/api/product/collect';
import { getPage as getCouponPage } from '@/api/promotion/couponInfo';
import { getDefault } from '@/api/user/address';
import { useGoodsStore } from '@/stores/goods';
import { useUserStore } from '@/stores/user';
import { Local } from '@/utils/storage';
import CouponInfo from '@/components/coupon-info/index.vue';
// 引入组件
import WaterfallGoods from '@/components/waterfall-goods/index.vue';
interface State {
	couponState: boolean; // 领券弹窗
	shareState: boolean; //分享弹窗
	moreState: boolean;
	isCanBack: boolean;
	goodsSpu: any; // 商品信息
	goodsAppraiseList: Array<any>; // 商品评价列表
	address: any; // 默认收货地址
	tabActive: number;
	selectArr: string;
	scrollStatus: boolean;
	couponList: Array<any>;
}
// 定义变量
const skuKey = ref(false);
const skuMode = ref(1);
const menuButtonTop = ref(10);
const loading = ref(true);
const storesGoodsStore = useGoodsStore();
const cellTtitleStyle = ref({
	paddingLeft: '50rpx',
	color: '#3a3a3a',
	fontSize: '24rpx',
});
const tabList = ref([
	{
		name: '商品',
		top: 0,
		height: 0,
	},
	{
		name: '评价',
		top: 0,
		height: 0,
	},
	{
		name: '详情',
		top: 0,
		height: 0,
	},
	{
		name: '推荐',
		top: 0,
		height: 0,
	},
]);
const state = reactive<State>({
	couponState: false, // 领券弹窗
	shareState: false, //分享弹窗
	moreState: false,
	isCanBack: false,
	goodsSpu: {}, // 商品信息
	goodsAppraiseList: [], // 商品评价列表
	address: {}, // 默认收货地址
	tabActive: 0,
	selectArr: '',
	scrollStatus: false,
	couponList: [],
});
const navBarHeight: any = ref(uni.getSystemInfoSync().statusBarHeight);
const proxy = getCurrentInstance()?.proxy;
onLoad((options) => {
	const id = options?.id;
	// 商品详情
	getSpu(id);
	// 通过商品id查询评价
	getGoodsAppraise(id);
	// 	获取已登录用户默认收货地址
	getDefaultAddress();
});
onPageScroll((res) => {
	state.scrollStatus = res.scrollTop > 100;
	// 处理tabs切换
	let index = tabList.value.findIndex((item) => res.scrollTop < item.top + item.height - navBarHeight.value - 60);
	state.tabActive = index >= 0 ? index : tabList.value.length - 1;
});
onMounted(async () => {
	// #ifdef MP
	try {
		const { top } = await uni.getMenuButtonBoundingClientRect();
		menuButtonTop.value = top;
	} catch (error) {
		console.error('获取胶囊按钮位置失败', error);
	}
	// #endif
	const pages = getCurrentPages();
	/**
	 * 判断是否能返回
	 */
	if (pages.length <= 1 || pages[pages.length - 1].route == 'pages/login/index') {
		state.isCanBack = false;
	} else {
		state.isCanBack = true;
	}
});
// 富文本渲染完成
const readyHandel = () => {
	getBoundingClientRect('#scroll-description')
		.then((data: any) => {
			tabList.value[2].top = data.top;
			tabList.value[2].height = data.height;
		})
		.catch((error) => {
			console.error(error);
		});
	getBoundingClientRect('#scroll-like')
		.then((data: any) => {
			tabList.value[3].top = data.top;
			tabList.value[3].height = data.height;
		})
		.catch((error) => {
			console.error(error);
		});
};
const goBack = () => {
	if (state.isCanBack) {
		uni.navigateBack({
			delta: 1,
		});
	} else {
		toHome();
	}
};
const openSkuPopup = (value: number) => {
	skuMode.value = value;
	skuKey.value = true;
};
const onCurrentPage = (item: any, index: number) => {
	uni.pageScrollTo({
		scrollTop: item.top - navBarHeight.value - 50,
	});
	state.tabActive = index;
};

// 商品分享
const goodsShare = () => {
	const user = Local.get('userInfo');
	uni.share({
		provider: 'weixin',
		scene: 'WXSceneSession',
		type: 0,
		href: 'pages/product/goods-detail/index?id=' + state.goodsSpu.id,
		title: state.goodsSpu.name,
		summary: state.goodsSpu.name,
		imageUrl: state.goodsSpu.spuUrls[0],
		success: function (res) {
			console.log('success:' + JSON.stringify(res));
		},
		fail: function (err) {
			console.log('fail:' + JSON.stringify(err));
		},
	});
};
// sku组件 开始-----------------------------------------------------------
const onOpenSkuPopup = () => {
	console.log('监听 - 打开sku组件');
};
const onCloseSkuPopup = (data: any) => {
	if (data) {
		state.selectArr = data.join(' ').trim();
	}
	console.log('监听 - 关闭sku组件');
};
// 打开优惠券弹窗
const showCoupon = () => {
	state.couponState = true;
};
// 通过id查询商品详情
const getSpu = (id: string) => {
	getSpuById(id).then((response) => {
		loading.value = false;
		state.goodsSpu = response.data;
		queryCoupon();
		if (state.goodsSpu.enableSpecs == '0') {
			state.goodsSpu.goodsSkus[0].goodsSkuSpecsValues = [
				{
					specsValueName: '默认',
				},
			];
			state.goodsSpu.goodsSpuSpecs = [
				{
					specsName: '默认',
					goodsSkuSpecsValues: [
						{
							specsValueName: '默认',
						},
					],
				},
			];
		}
		nextTick(() => {
			getBoundingClientRect('#scroll-pic')
				.then((data: any) => {
					tabList.value[0].top = data.top;
					tabList.value[0].height = data.height;
				})
				.catch((error) => {
					console.error(error);
				});
			getBoundingClientRect('#scroll-comment')
				.then((data: any) => {
					tabList.value[1].top = data.top;
					tabList.value[1].height = data.height;
				})
				.catch((error) => {
					console.error(error);
				});
		});
	});
};
function getBoundingClientRect(id: string) {
	return new Promise((resolve, reject) => {
		const query = uni.createSelectorQuery().in(proxy);
		query
			.select(id)
			.boundingClientRect((data) => {
				if (data) {
					resolve(data);
				} else {
					reject(new Error('Element not found or query failed'));
				}
			})
			.exec();
	});
}

// 通过id查询商品评价
const getGoodsAppraise = (id: string) => {
	getAppraisePage({
		spuId: id,
		current: 1,
		size: 3,
		desc: 'create_time',
	}).then((response) => {
		state.goodsAppraiseList = response.data.records;
	});
};
// 添加购物车
const addCart = (data: any) => {
	addShoppingCart(data).then((res) => {
		uni.showToast({
			title: '添加成功',
			icon: 'none',
			duration: 3000,
		});
		skuKey.value = false;
	});
};
// 立即购买
const buyNow = (data: any) => {
	storesGoodsStore.setGoodsInfo([data]);
	uni.$hxRouter.push({url:'/pages/order/order-confirm/index'}, true);
};
// 收藏
const handleCollect = () => {
	if (state.goodsSpu.collectId) {
		// 取消收藏
		deleteCollect(state.goodsSpu.collectId).then((response) => {
			state.moreState = false;
			state.goodsSpu.collectId = '';
		});
	} else {
		addCollect({ spuId: state.goodsSpu.id, salesPrice: state.goodsSpu.lowPrice }).then((response) => {
			state.moreState = false;
			state.goodsSpu.collectId = response.data.id;
		});
	}
};

//查询用户默认收货地址
const getDefaultAddress = () => {
	if (Local.getToken()) {
		getDefault().then((res) => {
			state.address = res.data;
		});
	}
};

// 查询优惠券
const queryCoupon = () => {
	getCouponPage({
		spuId: state.goodsSpu.id,
		current: 1,
		size: 50,
		desc: 'create_time',
	}).then((response) => {
		state.couponList = response.data.records;
	});
};

// 跳转收货地址
const toAddress = () => {
	uni.$hxRouter.push({url:'/pages/user/address/index'}, true);
};
// 跳转商品评价
const toAppraise = (id: string) => {
	uni.$hxRouter.push({url:'/pages/product/goods-appraise/index?spuId=' + id});
};
// 跳转首页
const toHome = () => {
	uni.$hxRouter.push({
		type: 'reLaunch',
		url: '/pages/home/index',
	});
};
// 跳转购物车
const toCart = () => {
	uni.$hxRouter.push({
		type: 'reLaunch',
		url: '/pages/user/shopping-cart/index',
	});
};
</script>

<style lang="scss">
.goods-detail-container {
	display: flex;
	flex-direction: column;
	width: 100%;
	height: 100%;
	box-sizing: border-box;

	.goods-detail-header {
		background-color: rgba(255, 255, 255, 0);
		/* #ifndef MP */
		padding: calc(var(--status-bar-height) + 5px) 10px 5px;
		/* #endif */
		/* #ifdef MP */
		padding: 0 10px 5px;
		/* #endif */
		display: flex;
		align-items: center;
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		box-shadow: 0 -1px #fff;
		box-sizing: border-box;
		z-index: 999;

		.goods-detail-warp {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			position: relative;
			height: 31px;

			.detail-header-back {
				position: relative;
				z-index: 1;

				.detail-header-back-icon {
					background-color: rgba(0, 0, 0, 0.3);
					border-radius: 100%;
					color: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
					width: 30px;
					height: 30px;
				}
			}

			.detail-header-back-bg {
				background-color: rgba(0, 0, 0, 0) !important;
				color: #3a3a3a !important;
			}

			.detail-header-content {
				font-size: 12px;
				position: absolute;
				width: 100%;
				height: 31px;

				.detail-header-content-nav {
					display: flex;
					justify-content: center;
					transition: all 0.3s ease;
					color: #3a3a3a;
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translate(-50%, -50%);

					.tab-item {
						margin-right: 20rpx;
					}

					.tab-item-active {
						font-weight: 700;
						position: relative;
						color: #2979ff;
					}
				}
			}

			.detail-header-right {
				display: flex;
				position: relative;
				z-index: 2;

				.detail-header-right-icon {
					background-color: rgba(0, 0, 0, 0.3);
					border-radius: 100%;
					color: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
					width: 30px;
					height: 30px;
				}
			}
		}
	}
}

.goods-detail-header-bg {
	background-color: rgba(255, 255, 255, 1) !important;
}

.goods-title-container {
	padding: 20rpx;

	.goods-price-warp {
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		border-radius: 10rpx;

		.goods-price {
			color: red;
			font-size: 40rpx;
		}

		.goods-sales {
			font-size: 22rpx;
			color: #909090;
		}
	}

	.coupon-warp {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 10rpx 20rpx 20rpx 20rpx;
		display: flex;
		align-items: center;
		width: 100%;
		justify-content: space-between;
	}

	.goods-title-warp {
		margin-top: 20rpx;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;

		.goods-title {
			font-size: 28rpx;
		}

		.sub-title {
			padding-top: 10rpx;
			font-size: 22rpx;
			color: #909090;
		}
	}

	.goods-cell-warp {
		margin-top: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 10rpx;
	}
}

.comment-container {
	padding: 20rpx;

	.comment-warp {
		background-color: #fff;
		border-radius: 10rpx;

		.comment-content {
			padding: 20rpx;

			.comment-content-title {
				display: flex;

				.right {
					padding-left: 20rpx;

					.create-time {
						font-size: 22rpx;
						color: #909090;
					}
				}
			}

			.comment-content-goods {
				padding-top: 10rpx;
				font-size: 22rpx;
				color: #909090;
			}

			.content {
				padding-top: 10rpx;
			}

			.content-images {
				display: flex;
				flex-wrap: wrap;
				align-items: flex-start;
				margin-top: 10rpx;

				.image-item {
					width: 33.33%;
					height: 100px;
					padding: 10rpx;
				}
			}
		}
	}
}

.parse-container {
	padding: 20rpx;

	.parse-warp {
		background-color: #fff;
		border-radius: 10rpx;

		.content {
			margin-top: 10rpx;
		}
	}
}

.like-container {
	padding: 20rpx;
}

.u-cell {
	padding: 10rpx !important;
}

.navigation {
	position: fixed;
	bottom: 0px;
	left: 0px;
	display: flex;
	margin-top: 100rpx;
	border: solid 2rpx #f2f2f2;
	background-color: #ffffff;
	padding: 16rpx 0;
	padding-bottom: calc(env(safe-area-inset-bottom) / 2);
	width: 100%;
	z-index: 1;

	.left {
		display: flex;
		font-size: 20rpx;

		.item {
			margin: 0 30rpx;

			&.car {
				text-align: center;
				position: relative;

				.car-num {
					position: absolute;
					top: -10rpx;
					right: -10rpx;
				}
			}
		}
	}

	.right {
		display: flex;
		font-size: 28rpx;
		align-items: center;

		.btn {
			line-height: 66rpx;
			padding: 0 30rpx;
			border-radius: 36rpx;
			color: #ffffff;
		}

		.cart {
			background-color: #ed3f14;
			margin-right: 30rpx;
		}

		.buy {
			background-color: #ff7900;
		}
	}
}

.coupons_css {
	height: 36upx;
	position: relative;
	margin-right: 20upx;
	text-align: center;
	line-height: 36upx;
	padding: 0 14upx;
	border: 1upx solid #ff3d36;
	border-radius: 10upx;
	font-size: 22upx;
	color: #ff3d36;
}

.leftdot {
	position: absolute;
	top: 13upx;
	left: -3upx;
	width: 6upx;
	height: 10upx;
	border-top-right-radius: 20upx;
	border-bottom-right-radius: 20upx;
	border: 1upx solid #ff3d36;
	background-color: #fff;
	border-left: 0;
}

.rightdot {
	position: absolute;
	top: 13upx;
	right: -3upx;
	width: 6upx;
	height: 10upx;
	border-top-left-radius: 20upx;
	border-bottom-left-radius: 20upx;
	border: 1upx solid #ff3d36;
	background-color: #fff;
	border-right: 0;
}

.share-container {
	position: fixed;
	bottom: 100px;
	right: 20rpx;
	background-color: rgba(0, 0, 0, 0);
	padding-left: 8px;
	padding-right: 8px;
	border-radius: 10px;
	border: 1px solid #f2f2f2;
	line-height: 1.8;
	margin: 40rpx 0;
}

.more-popup-container {
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 40rpx 0;

	.more-popup-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx;

		.text {
			color: #2979ff;
		}
	}
}
</style>
